package bhwz.seac3.db.nbadata;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import bhwz.seac3.db.Database;
import bhwz.seac3.dbservice.nbadata.SaveQueryDBService;
import bhwz.seac3.po.SimpleSaveQuery;

public class SaveQueryDB<SSQ extends SimpleSaveQuery> implements SaveQueryDBService<SSQ>{

	@Override
	public void save(SSQ po) throws Exception{
		Database.executeTransaction(s->{
			s.save(po);
		});
	}
	
	@Override
	public void deleteById(SSQ po) throws Exception {
		Database.executeTransaction(s->{
			s.delete(po);
		});
	}
	
	@Override
	public void updateById(SSQ po) throws Exception {
		Database.executeTransaction(s->{
			s.delete(po);
			s.save(po);
		});
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<SSQ> queryAll(Class c) throws Exception{
		List result=new ArrayList();
		Database.executeTransaction(s->{
			Query q=s.createQuery("from "+c.getName());
			q.list().forEach(e->{
					result.add((e));
			});			
		});
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public SSQ queryById(SSQ id) throws Exception{
		SimpleSaveQuery[] result=new SimpleSaveQuery[1];
		Database.executeTransaction(s->{
			result[0]=(SimpleSaveQuery) s.get(id.getClass(), id.getId());
		});
		return (SSQ) result[0];
	}	

}
